//
//  HistoryViewController.swift
//  beauties
//
//  Created by Shuai Liu on 15/7/1.
//  Copyright (c) 2015年 Shuai Liu. All rights reserved.
//

import Foundation
import UIKit

class HistoryViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource, UIScrollViewDelegate {
    
    // ---------------- Views
    var meiziCollectionView: UICollectionView!
    var refreshControl: UIRefreshControl!
    // ---------------- Data
    var meizis: [MeiziImageEntity]
    let sharedMargin = 10
    var page = 1
    var isLoadingNow = false
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        meizis = []
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }

    required init?(coder aDecoder: NSCoder) {
        meizis = []
        super.init(coder: aDecoder)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = ThemeColor
        self.edgesForExtendedLayout = .None
        self.automaticallyAdjustsScrollViewInsets = true
        
        let statusBarHeight: CGFloat = 20
        
        let collectionViewLayout = UICollectionViewFlowLayout()
        collectionViewLayout.itemSize = CGSizeMake((CGRectGetWidth(self.view.bounds) - 10 * 3) / 2, 200)
        collectionViewLayout.minimumLineSpacing = 10
        collectionViewLayout.minimumInteritemSpacing = 10
        collectionViewLayout.sectionInset = UIEdgeInsetsMake(0, 10, CGRectGetHeight(self.tabBarController!.tabBar.frame) + statusBarHeight + 10, 10)
        
        var frame = self.view.bounds
        frame.origin.y += statusBarHeight
        self.meiziCollectionView = UICollectionView(frame: frame, collectionViewLayout: collectionViewLayout)
        self.meiziCollectionView.alwaysBounceVertical = true
        self.meiziCollectionView.backgroundColor = UIColor.clearColor()
        self.meiziCollectionView.collectionViewLayout = collectionViewLayout
        self.meiziCollectionView.delegate = self
        self.meiziCollectionView.dataSource = self
        self.meiziCollectionView.registerClass(MeiziCollectionViewCell.self, forCellWithReuseIdentifier: "MeiziCollectionViewCell")
        self.meiziCollectionView.registerClass(MeiziCollectionViewFooter.self, forSupplementaryViewOfKind:UICollectionElementKindSectionFooter, withReuseIdentifier: "MeiziCollectionViewFoooter")
        self.view.addSubview(self.meiziCollectionView!)
        
        self.refreshControl = UIRefreshControl()
        self.refreshControl.addTarget(self, action: Selector("refreshData"), forControlEvents: .ValueChanged)
        self.meiziCollectionView.addSubview(self.refreshControl)
        
        // start loading data
        self.refreshData()
    }
    
    // MARK: fetch DATA
    
    func refreshData() {
        page = 1
        self.meizis.removeAll(keepCapacity: false)
        self.fetchNextPage(page)
    }
    
    func fetchNextPage(page: Int) {
        if (self.page > MeiziDateUtil.MAX_PAGE) {
            return
        }
        if (self.isLoadingNow) {
            return
        }
        
        self.isLoadingNow = true
        print("---------- Starting Page \(page) ----------")
        
        NetworkUtil.getBeauties(page) {
            [weak self] result, error in
            print("---------- Finished Page \(page) ----------")
            
            if let sself = self {
                
                sself.isLoadingNow = false
                sself.refreshControl.endRefreshing()
                
                if error == nil {
                    sself.page += 1
                    sself.meizis += result.map(sself.buildEntityWithURLString)
                    sself.setBGI()
                    sself.meiziCollectionView.reloadData()
                }
            }
        }
    }
    
    // set Blur Background Image
    func setBGI() {
        if self.meizis.count == 0 {
            return
        }
        let beautyEntity = self.meizis[0]
        
        let bgi = UIImageView(frame: self.view.bounds)
        bgi.contentMode = .ScaleToFill
        self.view.addSubview(bgi)
        self.view.sendSubviewToBack(bgi)
        
        bgi.kf_setImageWithURL(NSURL(string: beautyEntity.imageUrl!)!, placeholderImage: nil, optionsInfo: nil) {
            image, error, cacheType, imageURL in
            bgi.applyBlurEffect()
        }
    }
    
    func buildEntityWithURLString(url: String) -> MeiziImageEntity {
        let b = MeiziImageEntity()
        b.imageUrl = url
        return b
    }
    
    // MARK: UIScrollViewDelegate
    func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if (scrollView.contentOffset.y + CGRectGetHeight(scrollView.bounds) > scrollView.contentSize.height) {
            self.fetchNextPage(self.page)
        }
    }
    
    // MARK: UICollectionViewDataSource
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return meizis.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MeiziCollectionViewCell", forIndexPath: indexPath) as! MeiziCollectionViewCell
        if (indexPath.row < meizis.count) {
            let entity = meizis[indexPath.row]
            cell.bindData(entity)
        }
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
        let footer: MeiziCollectionViewFooter = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "MeiziCollectionViewFoooter", forIndexPath: indexPath) as! MeiziCollectionViewFooter
        if (kind == UICollectionElementKindSectionFooter) {
            footer.startAnimating()
        }
        return footer
    }
    
    // MARK: UICollectionViewDelegate
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        if (indexPath.row < self.meizis.count) {
            let entity = self.meizis[indexPath.row]
            let todayViewController = TodayViewController()
            todayViewController.todayMeizi = entity
            todayViewController.canBeClosed = true
            self.presentViewController(todayViewController, animated: true, completion: nil)
        }
    }
    
    // MARK: UICollectionViewDelegateFlowLayout
    
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        if page >= MeiziDateUtil.MAX_PAGE {
            return CGSizeZero
        } else {
            return CGSizeMake(CGRectGetWidth(collectionView.bounds), 50)
        }
    }
}